// Copyright 2017 Baidu Inc. All Rights Reserved.
// Author: Su Hao (suhao@baidu.com)
//
// Description: socket adapter implementation

#include "baidu_ca_network_adapter.h"
#include "baidu_ca_adapter.h"
#include "baidu_ca_network_socket.h"
#include "heap_monitor.h"

using duer::SocketAdapter;

bca_socket_t bca_soc_create(bca_context ctx) {
    SocketAdapter* rs = NEW(CA) SocketAdapter();

    if (rs && ctx) {
        SocketAdapter::Callback* cb = reinterpret_cast<SocketAdapter::Callback*>(ctx);
        rs->attach(*cb);
    }

    return rs;
}

bca_status_t bca_soc_connect(bca_socket_t ctx, const bca_addr_t* addr) {
    SocketAdapter* soc = reinterpret_cast<SocketAdapter*>(ctx);
    return soc->connect(addr);
}

bca_status_t bca_soc_send(bca_socket_t ctx, const void* data, bca_size_t size,
                          const bca_addr_t* addr) {
    SocketAdapter* soc = reinterpret_cast<SocketAdapter*>(ctx);
    return soc ? soc->send(data, size) : BCA_ERR_INTERNAL;
}

bca_status_t bca_soc_recv(bca_socket_t ctx, void* data, bca_size_t size,
                          bca_addr_t* addr) {
    SocketAdapter* soc = reinterpret_cast<SocketAdapter*>(ctx);
    return soc ? soc->recv(data, size) : BCA_ERR_INTERNAL;
}

bca_status_t bca_soc_close(bca_socket_t ctx) {
    SocketAdapter* soc = reinterpret_cast<SocketAdapter*>(ctx);
    return soc ? soc->close() : BCA_ERR_INTERNAL;
}

bca_status_t bca_soc_destroy(bca_socket_t ctx) {
    SocketAdapter* soc = reinterpret_cast<SocketAdapter*>(ctx);
    delete soc;
    return BCA_NO_ERR;
}
